package org.example.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.entity.*;

import java.io.File;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ProxyTester {
    private static final int TIMEOUT_MS = 5000;
    private static final int THREAD_POOL_SIZE = 10;

    public static void main(String[] args) {
        String configPath = "C:\\software\\v2rayN-With-Core\\guiConfigs\\configSpeedtest.json";
        
        try {
            ConfigSpeedtest config = loadConfig(configPath);
            List<TestServer> testServers = extractTestServers(config);
            testProxies(testServers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static ConfigSpeedtest loadConfig(String configPath) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(new File(configPath), ConfigSpeedtest.class);
    }

    private static List<TestServer> extractTestServers(ConfigSpeedtest config) {
        List<TestServer> testServers = new ArrayList<>();
        
        for (Outbound outbound : config.getOutbounds()) {
            // 跳过direct和block类型的出站
            if ("direct".equals(outbound.getTag()) || "block".equals(outbound.getTag())) {
                continue;
            }
            
            // 处理VLESS协议
            if ("vless".equals(outbound.getProtocol()) && outbound.getSettings() != null 
                && outbound.getSettings().getVnext() != null) {
                for (Vnext vnext : outbound.getSettings().getVnext()) {
                    TestServer testServer = new TestServer();
                    testServer.setAddress(vnext.getAddress());
                    testServer.setPort(vnext.getPort());
                    testServer.setProtocol(outbound.getProtocol());
                    testServer.setTag(outbound.getTag());
                    testServers.add(testServer);
                }
            }
            
            // 处理Shadowsocks协议
            else if ("shadowsocks".equals(outbound.getProtocol()) && outbound.getSettings() != null 
                     && outbound.getSettings().getServers() != null) {
                for (Server server : outbound.getSettings().getServers()) {
                    TestServer testServer = new TestServer();
                    testServer.setAddress(server.getAddress());
                    testServer.setPort(server.getPort());
                    testServer.setProtocol(outbound.getProtocol());
                    testServer.setTag(outbound.getTag());
                    testServers.add(testServer);
                }
            }
        }
        
        return testServers;
    }

    private static void testProxies(List<TestServer> testServers) {
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
        List<Future<TestResult>> futures = new ArrayList<>();
        
        for (TestServer server : testServers) {
            Future<TestResult> future = executor.submit(() -> testProxy(server));
            futures.add(future);
        }
        
        System.out.println("开始测试 " + testServers.size() + " 个服务器...");
        System.out.println("=".repeat(50));
        
        for (Future<TestResult> future : futures) {
            try {
                TestResult result = future.get();
                System.out.printf("服务器: %s:%d (%s) - %s (耗时: %d ms)%n",
                        result.getAddress(), result.getPort(), result.getTag(),
                        result.isSuccess() ? "成功" : "失败", result.getLatency());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        
        executor.shutdown();
    }

    private static TestResult testProxy(TestServer server) {
        TestResult result = new TestResult();
        result.setAddress(server.getAddress());
        result.setPort(server.getPort());
        result.setTag(server.getTag());
        
        try {
            long startTime = System.currentTimeMillis();
            
            // 创建Socket连接测试
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(server.getAddress(), server.getPort()), TIMEOUT_MS);
            socket.close();
            
            long endTime = System.currentTimeMillis();
            result.setSuccess(true);
            result.setLatency(endTime - startTime);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setLatency(-1);
        }
        
        return result;
    }
}
